package com.heima.common.exception;

import com.heima.common.dtos.ResponseResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice  //指定当前类是统一异常处理类
public class ExceptionCatch {

    @ExceptionHandler(RuntimeException.class)//指定当前方法处理那种异常
    public ResponseResult runTimeException(RuntimeException e){
        e.printStackTrace();
        return ResponseResult.error(500,e.getMessage());
    }

    @ExceptionHandler(LeadException.class)
    public ResponseResult leadException(LeadException e){
        e.printStackTrace();
        return ResponseResult.error(e.getStatus(),e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult mthodArgumenException(MethodArgumentNotValidException e){

        List<ObjectError> objectErrorList = e.getBindingResult().getAllErrors();
        String msg = objectErrorList.stream().
                map(ObjectError::getDefaultMessage).
                collect(Collectors.joining(","));
        return ResponseResult.error(400,msg);
    }

}
